<?php

require '../classes/Conf.php';
require '../classes/Connection.php';
require '../classes/ConnectionSecure.php';
require '../classes/Usuarios.php';


//include('inicializar.php');
$post_names = array('username', 'first_name', 'last_name', 'phone', 'email', 'pass', 'pass_r', 'type');
foreach ($post_names as $key => $value) {
    if (!isset($_POST[$value])) {
        echo "Faltan datos";
        return;
    }
}
$error = "";
$username = "";
$first_name = "";
$last_name = "";
$phone = "";
$email = "";
$type = "";
$pass = "";
$pass_r = "";


$username = addslashes(trim($_POST['username']));
$first_name = addslashes(trim($_POST['first_name']));
$last_name = addslashes(trim($_POST['last_name']));
$phone = addslashes(trim($_POST['phone']));
$email = addslashes(trim($_POST['email']));
$type = $_POST['type'] + 0;
$pass = addslashes(trim($_POST['pass']));
$pass_r = addslashes(trim($_POST['pass_r']));

if ($pass == '') {
    echo "The password is mandatory.";
} else if ($pass != $pass_r) {
    echo "Both passwords must match.";
}
else if (strlen($pass) < 6) {
   echo "Password too short!";
}
else if (!preg_match("#[0-9]+#", $pass)) {
    echo  "Password must include at least one number!";
}
else if (!preg_match("#[a-zA-Z]+#", $pass)) {
    echo "Password must include at least one letter!";
} else if ($username == "") {
    echo "The username is mandatory.";
} else if ($email == "") {
    echo "The e-mail address is mandatory.";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo "The e-mail address is not a valid e-mail";
}else {
    $usuarioOBJ = new Usuarios();
    if (strcmp($usuarioOBJ->idFromUsuarioOrEmail($username, $email), '-1') != 0) {
        echo "El usuario y/o email ya existen";
        return;
    } else {
        $id = $usuarioOBJ->insertar($username, $first_name, $last_name, $phone, $email);
        if ($id > 0) {
            $usuarioOBJ->insertarRol($id, $type);
            $usuarioOBJ->insertarClave($id, $pass);
            echo "Registrado satisfactoriamente";
        } else {
            echo "Ocurrio un error inesperado";
        }
    }
}
?>
 
